<template>
  <div class="group-buy-edit-container">
    <el-card title="编辑团购活动">
      <!-- 表单主体 -->
      <el-form
          ref="groupBuyForm"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="group-buy-form"
      >
        <!-- 基础信息区域 -->
        <el-divider content="基础信息" />
        <el-form-item label="团购编号" prop="id">
          <el-input v-model="formData.id" disabled placeholder="系统自动生成" />
        </el-form-item>

        <el-form-item label="关联团购ID" prop="merchantId">
          <el-input v-model="formData.merchantId" disabled placeholder="关联的团购ID" />
        </el-form-item>

        <el-form-item label="团购名称" prop="name">
          <el-input
              v-model="formData.name"
              placeholder="请输入团购活动名称"
              maxlength="50"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="团购描述" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入团购活动描述"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="原价" prop="price">
          <el-input
              v-model.number="formData.price"
              placeholder="请输入商品原价"
              type="number"
              step="0.01"
              min="0.01"
          >
            <template #prefix>
              <span style="margin-left: 8px; color: #666">¥</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="折扣价" prop="discount">
          <el-input
              v-model.number="formData.discount"
              placeholder="请输入团购折扣价"
              type="number"
              step="0.01"
              min="0.01"
          >
            <template #prefix>
              <span style="margin-left: 8px; color: #666">¥</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="团购限制人数" prop="personNum">
          <el-input
              v-model.number="formData.personNum"
              placeholder="请输入每单限制人数"
              type="number"
              min="1"
          />
          <div class="form-hint">注：每人限参与1次，限制人数为每单最大参与人数</div>
        </el-form-item>

        <!-- 商品列表区域 -->
        <el-divider content="包含商品列表" />
        <div class="goods-list-section">
          <!-- 无商品提示 -->
          <div v-if="formData.goodsList.length === 0" class="no-goods">
            <el-icon class="no-goods-icon">
              <ShoppingCart />
            </el-icon>
            <p class="no-goods-text">当前暂无商品，点击「新增商品」添加</p>
          </div>

          <!-- 商品表格（完整保留所有列） -->
          <el-table
              v-else
              border
              stripe
              :data="formData.goodsList"
              style="width: 100%; margin-bottom: 15px"
          >
            <!-- 关联团购ID列（隐藏输入，仅显示，确保merchantId正确） -->
            <el-table-column prop="merchantId" label="关联团购ID" width="150" align="center" />

            <!-- 商品ID列 -->
            <el-table-column prop="id" label="商品ID" width="120" align="center">
              <template #default="scope">
                <el-input
                    v-model.number="scope.row.id"
                    placeholder="输入商品ID"
                    type="number"
                    min="1"
                />
              </template>
            </el-table-column>

            <!-- 商品名称列 -->
            <el-table-column prop="name" label="商品名称" align="center" width="250">
              <template #default="scope">
                <el-input
                    v-model="scope.row.name"
                    placeholder="输入商品名称"
                    maxlength="30"
                    show-word-limit
                />
              </template>
            </el-table-column>

            <!-- 数量列 -->
            <el-table-column prop="num" label="数量" width="120" align="center">
              <template #default="scope">
                <el-input
                    v-model.number="scope.row.num"
                    placeholder="输入数量"
                    type="number"
                    min="1"
                />
              </template>
            </el-table-column>

            <!-- 单价列 -->
            <el-table-column prop="price" label="单价" width="120" align="center">
              <template #default="scope">
                <el-input
                    v-model.number="scope.row.price"
                    placeholder="输入单价"
                    type="number"
                    step="0.01"
                    min="0.01"
                >
                  <template #prefix>
                    <span style="margin-left: 8px; color: #666">¥</span>
                  </template>
                </el-input>
              </template>
            </el-table-column>

            <!-- 小计列（只读，实时计算） -->
            <el-table-column label="小计" width="120" align="center">
              <template #default="scope">
                ¥{{ formatPrice((scope.row.price || 0) * (scope.row.num || 0)) }}
              </template>
            </el-table-column>

            <!-- 操作列（删除按钮） -->
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                    type="text"
                    color="#ff4d4f"
                    @click="() => removeGoods(scope)"
                    class="group-buy-delete-btn"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增商品按钮（始终显示） -->
          <el-button
              type="text"
              icon="Plus"
              @click="addGoods"
              class="add-goods-btn"
          >
            新增商品
          </el-button>

          <!-- 商品总价统计（有商品时显示） -->
          <div class="goods-total" v-if="formData.goodsList.length > 0">
            <span>商品总价：</span>
            <span class="total-price">¥{{ formatPrice(calculateTotalGoodsPrice()) }}</span>
          </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <el-button @click="handleBack">取消</el-button>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElDivider, ElIcon } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import server from "../utils/request.js";
import { Plus, ShoppingCart } from '@element-plus/icons-vue';
import {getUserIdFromToken} from "../utils/jwtUtil.js";
// 路由相关
const route = useRoute();
const router = useRouter();
const merchantId = getUserIdFromToken()
// 表单实例
const groupBuyForm = ref(null);

// 存储路由传递的团购ID（用于给所有商品赋值merchantId）
const groupBuyId = ref('');

// 表单数据（完整保留所有字段）
const formData = ref({
  id: '',
  merchantId: '', // 团购关联ID（与商品merchantId一致）
  name: '',
  description: '',
  price: 0, // 原价
  discount: 0, // 折扣价
  personNum: 1, // 限制人数
  goodsList: [] // 商品列表（每个商品包含merchantId、id、name、num、price）
});

// 表单验证规则（完整保留）
const formRules = reactive({
  name: [
    { required: true, message: '请输入团购活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2-50 个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述不能超过 500 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '原价必须大于 0', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣价', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '折扣价必须大于 0', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value >= formData.value.price) {
          callback(new Error('折扣价必须小于原价'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  personNum: [
    { required: true, message: '请输入限制人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '限制人数至少为 1', trigger: 'blur' }
  ]
});

// 页面挂载时：接收参数 + 回显数据 + 商品赋值merchantId
onMounted(() => {
  // 1. 接收路由query中的id（团购ID）
  const queryId = route.query.id;
  if (!queryId) {
    ElMessage.error('缺少团购ID，无法编辑');
    router.push('/merchantGroupBuyList');
    return;
  }

  // 2. 存储团购ID（根据后端需求转换类型）
  groupBuyId.value = queryId; // 需数字则改为：Number(queryId)

  // 3. 给团购本身的merchantId赋值
  formData.value.merchantId = merchantId;

  // 4. 获取团购详情并回显
  fetchGroupBuyDetail(queryId);
});

// 获取团购详情（回显并给商品赋值merchantId）
const fetchGroupBuyDetail = async (id) => {
  try {
    const { data } = await server.post(`groupBuy/${id}`);
    if (data.code === 200 && data.data[0]) {
      const detail = data.data[0];
      // 给每个商品强制赋值merchantId = 路由传递的团购ID
      const goodsListWithMerchantId = (detail.goodsList || []).map(goods => ({
        ...goods,
        merchantId: merchantId// 核心：统一关联团购ID
      }));

      // 完整回显数据
      formData.value = {
        ...detail,
        merchantId: merchantId,
        goodsList: goodsListWithMerchantId,
        price: detail.price || 0,
        discount: detail.discount || 0,
        personNum: detail.personNum || 1
      };
    } else {
      ElMessage.error('获取团购详情失败：' + (data.msg || '未知错误'));
      router.push('/merchantGroupBuyList');
    }
  } catch (error) {
    console.error('获取详情异常：', error);
    ElMessage.error('网络错误，加载失败');
    router.push('/merchantGroupBuyList');
  }
};

// 格式化价格（保留两位小数）
const formatPrice = (price) => {
  if (!price && price !== 0) return '0.00';
  return Number(price).toFixed(2);
};

// 计算商品总价
const calculateTotalGoodsPrice = () => {
  if (formData.value.goodsList.length === 0) return 0;
  return formData.value.goodsList.reduce((total, item) => {
    const itemPrice = Number(item.price) || 0;
    const itemNum = Number(item.num) || 0;
    return total + itemPrice * itemNum;
  }, 0);
};

// 新增商品（自动赋值merchantId）
const addGoods = () => {
  formData.value.goodsList.push({
    merchantId: merchantId, // 自动关联团购ID
    id: '', // 商品ID
    name: '', // 商品名称
    num: 1, // 数量（默认1）
    price: 0 // 单价（默认0）
  });

  // 滚动到最后一行
  nextTick(() => {
    const table = document.querySelector('.el-table__body-wrapper');
    if (table) table.scrollTop = table.scrollHeight;
  });
};

// 删除商品（允许删到空）
const removeGoods =async (scope) => {
  console.log("*****"+scope.row.id)
  formData.value.goodsList = formData.value.goodsList.filter((_, i) => i !== scope.index);
  if (scope.row.id!=null&&scope.row.id!=''){
    let {data:data} = await server.delete(`goods/${scope.row.id}`)
  }
  ElMessage.success('商品已删除');
  location.reload()
};

// 表单提交（兜底校验merchantId）
const submitForm = async () => {
  try {
    // 1. 基础表单验证
    await groupBuyForm.value.validate();

    // 2. 商品列表验证（有商品时校验必填项）
    if (formData.value.goodsList.length > 0) {
      const invalidGoods = formData.value.goodsList.find(item =>
          !item.name || !item.num || !item.price
      );
      if (invalidGoods) {
        ElMessage.error('请完善所有商品名称、数量和单价');
        return;
      }
    }

    // 3. 兜底：确保所有商品merchantId正确
    const finalGoodsList = formData.value.goodsList.map(goods => ({
      ...goods,
      merchantId: merchantId
    }));

    // 4. 提交数据
    const submitData = {
      ...formData.value,
      goodsList: finalGoodsList
    };
    const { data } = await server.put('/groupBuy', submitData);

    if (data.code === 200) {
      ElMessage.success('修改成功！');
      router.push('/merchantGroupBuyList');
    } else {
      ElMessage.error(`修改失败：${data.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 返回列表页
const handleBack = () => {
  router.push('/merchantGroupBuyList');
};
</script>

<style scoped>
/* 基础样式 */
.group-buy-edit-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.group-buy-form {
  padding: 20px 0;
}

/* 分割线样式 */
.el-divider--content-center .el-divider__text {
  font-size: 16px;
  font-weight: 500;
  color: #1f2329;
}

/* 商品列表区域 */
.goods-list-section {
  margin: 20px 0;
}

/* 无商品提示 */
.no-goods {
  text-align: center;
  padding: 40px 20px;
  background-color: #f9fafb;
  border-radius: 8px;
  margin-bottom: 15px;
}

.no-goods-icon {
  font-size: 32px;
  color: #c0c4cc;
  margin-bottom: 12px;
}

.no-goods-text {
  color: #666;
  font-size: 14px;
}

/* 新增商品按钮 */
.add-goods-btn {
  color: #409eff;
  margin-bottom: 10px;
}

/* 商品总价 */
.goods-total {
  text-align: right;
  margin-top: 10px;
  font-size: 15px;
  color: #1f2329;
}

.total-price {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 16px;
  margin-left: 8px;
}

/* 表单提示 */
.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #666;
}

/* 操作按钮区域 */
.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 修复删除按钮透明禁用问题 */
::v-deep .el-button--text.group-buy-delete-btn {
  opacity: 1 !important;
  pointer-events: auto !important;
  color: #ff4d4f !important;
  cursor: pointer !important;
}

::v-deep .el-button--text.group-buy-delete-btn:hover {
  color: #ff7875 !important;
  background-color: rgba(255, 77, 79, 0.05) !important;
}

/* 输入框聚焦优化 */
.el-input:focus-within .el-input__wrapper {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>